<?php

namespace App\Lib;

use EasySwoole\HttpClient\HttpClient;

/**
 * 封装curl请求
 */
class Curl
{
    /**
     * @param string $method
     * @param string $url
     * @param string|null $sendData    发送的json格式数据
     * @param array $head    设置http请求头
     * @return String
     */
    public function request(string $method, string $url, string $sendData = null, array $head = []): String
    {
        //设置发送的url
        $client = new HttpClient($url);

        $client->setClientSettings(['timeout' => 30, 'connect_timeout'=>30]);//配置客户端的配置(将覆盖原有配置),可参考https://wiki.swoole.com/wiki/page/726.html
        $client->setHeaders([
                'User-Agent'      => 'EasySwooleHttpClient/0.1',
                //
                // 'Access-Control-Allow-Origin'    => '*',
                // 'Access-Control-Allow-Methods'    => 'POST,GET,OPTIONS,DELETE',
                'Accept'          => 'text/html,application/xhtml+xml,application/xml',
                'Accept-Encoding' => 'gzip',
                'Pragma'          => 'no-cache',
                'Cache-Control'   => 'no-cache'
            ]);

        if (count($head) > 0) {
            foreach ($head as $key => $value) {
                if (!empty($value)) {
                    $client->setHeaders([
                        $key => $value
                    ], true, false);
                }
            }
        }

        // //发送一段post json内容
        // $client->postJson($sendData);
        switch ($method) {
            case 'GET':
                $response = $client->get();//发送get请求
                break;
            case 'POST':
                // $response = $client->post($sendData);//发送post请求
                $response = $client->post($sendData);
                break;
            case 'OPTIONS':
                $response = $client->options();//发送options请求
                break;
            default:
                throw new \InvalidArgumentException("method error");
                break;
        }

        return $response->getBody();
    }
}
